﻿using FSM.Bll;
using FSM.IBll;
using FSM.Model;
using FSM.Web.Models;
using FSM.Web.Models.Fileter;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace FSM.Web.Controllers
{
    public class LoginController : Controller
    {
        #region 模块

        private readonly DataResultModel drm = new DataResultModel();

        private readonly ISysUserBll _bll;

        private readonly ILogLoginBll _logLoginBll;

        private readonly IHttpContextAccessor _httpContextAccessor;

        private readonly ILogger<LoginController> _logger;

        #endregion

        #region 构造函数

        public LoginController(ISysUserBll bll, ILogLoginBll logLoginBll, IHttpContextAccessor httpContextAccessor, ILogger<LoginController> logger)
        {
            this._bll = bll;
            this._logLoginBll = logLoginBll;
            this._httpContextAccessor = httpContextAccessor;
            this._logger = logger;
        }

        #endregion

        public IActionResult Index()
        {
            string userNo = AuthencationHelper.GetLoginUserNo(User);
            if (string.IsNullOrEmpty(userNo))
            {
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        [HttpPost]
        [ResultExceptionFilter]
        [ValidateAntiForgeryToken]
        public JsonResult Valid(string user_no, string user_pwd, int terminal)
        {
            user_no = user_no?.ToUpper();
            log_login log = new log_login()
            {
                log_date = DateTime.Now,
                log_ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(),
                log_terminal = terminal,
                log_type = 1,
                log_user = user_no
            };

            var insertLoginLog = new Action<int, string>((status, memo) =>
            {
                log.log_status = status;
                log.log_memo = memo;
                try
                {
                    _logLoginBll.Insert(log);
                }
                catch (Exception ex)
                {
                    _logger.LogError(EventType.Login, ex.Message);
                }
            });

            try
            {
                bool success = _bll.ValidLogin(user_no, user_pwd);
                if (!success)
                {
                    insertLoginLog(0, "验证失败");
                    throw new Exception(log.log_memo);
                }
            }
            catch (Exception ex)
            {
                insertLoginLog(0, ex.Message);
                throw;
            }

            sys_user user = _bll.Get(user_no);

            //把登录人员存入Cookies
            var claimsIdentity = new ClaimsIdentity("ui_cookies");
            claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.user_no));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.user_name));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Sid, user.user_no));
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            HttpContext.SignInAsync(claimsPrincipal);

            insertLoginLog(1, "");

            drm.success = true;
            return drm.ToJson();
        }
    }
}
